import React, { useState } from "react";
import {
  Card,
  Typography,
  Space,
  Button,
  List,
  Tag,
  Spin,
  Empty,
  Alert,
  Divider,
  message,
} from "antd";
import {
  RobotOutlined,
  BulbOutlined,
  ThunderboltOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type { ClassPerformance, StudentPerformance } from "../types";
import { API_ENDPOINTS } from "../../../../config/env";
import { httpPost } from "../../../../utils/http";

const { Title, Text, Paragraph } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const SuggestionItem = styled.div`
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 16px;
`;

interface AIAnalysisProps {
  classPerformance?: ClassPerformance;
  studentPerformance?: StudentPerformance;
  studentName?: string;
}

const AIAnalysis: React.FC<AIAnalysisProps> = ({
  classPerformance,
  studentPerformance,
  studentName,
}) => {
  const [loading, setLoading] = useState(false);
  const [suggestions, setSuggestions] = useState<{
    teaching?: string[];
    improvement?: string[];
    resources?: string[];
  }>({});

  // 生成教学建议
  const generateSuggestions = async () => {
    setLoading(true);
    try {
      // 获取用户信息
      const userStr = localStorage.getItem('user');
      const user = userStr ? JSON.parse(userStr) : null;
      const userInfo = {
        account_id: user?.id?.toString() || "default_user",
        course_id: user?.currentCourseId?.toString() || "default_course"
      };

      let prompt = "";
      if (classPerformance) {
        // 班级整体分析
        prompt = `你是一个专业的教学分析师，请基于以下班级学习数据，生成具体的教学建议：

班级整体学习情况分析：
- 班级规模和基本信息
- 学习成绩分布情况  
- 学习活跃度和参与度
- 作业完成质量和及时性
- 课堂互动表现

请分别从以下三个方面给出专业的建议：

**1. 教学方法改进建议**
- 针对当前教学效果的优化策略
- 适合班级特点的教学方式调整
- 提升学生参与度的具体方法
- 课堂管理和时间安排优化

**2. 学生能力提升建议**  
- 识别学生的薄弱环节
- 个性化学习指导方案
- 学习方法和技巧培训
- 激发学习动机的策略

**3. 学习资源推荐**
- 针对性的教学材料推荐
- 在线学习平台和工具
- 实践项目和案例资源
- 评估和测试工具建议

请提供具体、可操作的建议，确保每条建议都有实际的应用价值。`;
      } else if (studentName) {
        // 个人分析
        prompt = `你是一个专业的学习顾问，请基于学生${studentName}的学习表现，生成个性化的教学建议：

学生个人学习情况分析：
- 学习成绩趋势和波动
- 学习习惯和时间管理
- 课堂参与度和互动表现
- 作业质量和提交情况
- 学习困难和挑战

请分别从以下三个方面给出针对性建议：

**1. 教学方法调整建议**
- 适合该学生的教学策略
- 个性化的讲解方式
- 有效的反馈和指导方法
- 课堂互动的改进措施

**2. 个人能力提升建议**
- 学习方法的具体指导
- 薄弱知识点的针对性训练
- 学习效率的提升方案
- 自主学习能力的培养

**3. 学习资源推荐**
- 个性化的学习材料
- 适合的在线课程和工具
- 练习题和实践项目
- 学习进度跟踪工具

请确保建议具有针对性和可操作性，有助于学生的实际学习提升。`;
      }

      // 调用Python AI服务
      const response = await fetch("http://localhost:8000/api/teach/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: prompt,
          account_id: userInfo.account_id,
          course_id: userInfo.course_id,
        }),
      });

      if (!response.ok) {
        throw new Error(`AI分析失败: ${response.status}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取AI响应流");
      }

      let aiResponse = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        aiResponse += chunk;
      }

      if (aiResponse) {
        // 解析AI建议，按类别分组
        const lines = aiResponse.split("\n").filter(line => line.trim());
        
        const teachingSuggestions: string[] = [];
        const improvementSuggestions: string[] = [];
        const resourceSuggestions: string[] = [];
        
        let currentCategory = "";
        
        lines.forEach(line => {
          const trimmedLine = line.trim();
          
          // 识别类别标题
          if (trimmedLine.includes("教学方法") || trimmedLine.includes("教学策略")) {
            currentCategory = "teaching";
          } else if (trimmedLine.includes("能力提升") || trimmedLine.includes("学习能力")) {
            currentCategory = "improvement";
          } else if (trimmedLine.includes("资源推荐") || trimmedLine.includes("学习资源")) {
            currentCategory = "resources";
          } else if (trimmedLine.startsWith("-") || trimmedLine.startsWith("•") || 
                     trimmedLine.match(/^\d+\./) || trimmedLine.match(/^[a-zA-Z]\)/)) {
            // 提取建议内容
            const suggestion = trimmedLine.replace(/^[-•\d\.a-zA-Z\)]\s*/, "").trim();
            if (suggestion.length > 10) { // 过滤太短的内容
              switch (currentCategory) {
                case "teaching":
                  teachingSuggestions.push(suggestion);
                  break;
                case "improvement":
                  improvementSuggestions.push(suggestion);
                  break;
                case "resources":
                  resourceSuggestions.push(suggestion);
                  break;
              }
            }
          }
        });

        // 设置解析后的建议
        setSuggestions({
          teaching: teachingSuggestions.length > 0 ? teachingSuggestions : [
            "采用多元化教学方法，结合理论与实践",
            "增加课堂互动环节，提升学生参与度",
            "定期进行教学效果评估和调整"
          ],
          improvement: improvementSuggestions.length > 0 ? improvementSuggestions : [
            "制定个性化学习计划，关注个体差异",
            "加强基础知识巩固和能力训练",
            "培养学生的自主学习能力"
          ],
          resources: resourceSuggestions.length > 0 ? resourceSuggestions : [
            "推荐优质在线学习平台和课程资源",
            "提供多样化的实践项目和案例材料",
            "建立学习资源库和知识管理系统"
          ]
        });

        message.success("AI分析建议生成成功！");
      } else {
        throw new Error("AI服务返回空响应");
      }
    } catch (error) {
      console.error("AI建议生成失败:", error);
      message.error("AI分析失败，请稍后重试");
      
      // 提供默认建议
      setSuggestions({
        teaching: [
          "建议采用混合式教学方法",
          "增加实践操作和案例分析",
          "定期收集学生反馈并调整教学策略"
        ],
        improvement: [
          "关注学生个体差异，提供针对性指导",
          "加强基础知识巩固和能力训练",
          "培养学生的自主学习能力"
        ],
        resources: [
          "整合优质在线教学资源",
          "建立多媒体教学资料库",
          "推荐专业学习工具和平台"
        ]
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <StyledCard
        title={
          <Space>
            <RobotOutlined />
            <span>AI 分析与建议</span>
          </Space>
        }
        extra={
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={generateSuggestions}
            loading={loading}
          >
            生成建议
          </Button>
        }
      >
        {loading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin
              indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
              tip="正在分析数据，生成建议..."
            />
          </div>
        ) : !suggestions.teaching ? (
          <Empty
            description={<span>点击&quot;生成建议&quot;按钮开始 AI 分析</span>}
          />
        ) : (
          <Space direction="vertical" style={{ width: "100%" }}>
            <div>
              <Title level={5}>
                <BulbOutlined /> 教学建议
              </Title>
              <List
                dataSource={suggestions.teaching}
                renderItem={(item) => (
                  <SuggestionItem>
                    <Paragraph style={{ marginBottom: 0 }}>{item}</Paragraph>
                  </SuggestionItem>
                )}
              />
            </div>

            <Divider />

            <div>
              <Title level={5}>
                <BulbOutlined /> 改进建议
              </Title>
              <List
                dataSource={suggestions.improvement}
                renderItem={(item) => (
                  <SuggestionItem>
                    <Paragraph style={{ marginBottom: 0 }}>{item}</Paragraph>
                  </SuggestionItem>
                )}
              />
            </div>

            <Divider />

            <div>
              <Title level={5}>
                <BulbOutlined /> 推荐资源
              </Title>
              <List
                dataSource={suggestions.resources}
                renderItem={(item) => (
                  <SuggestionItem>
                    <Paragraph style={{ marginBottom: 0 }}>{item}</Paragraph>
                  </SuggestionItem>
                )}
              />
            </div>

            <Alert
              message="AI 建议仅供参考"
              description="以上建议由 AI 根据数据分析生成，请结合实际情况合理使用。"
              type="info"
              showIcon
            />
          </Space>
        )}
      </StyledCard>
    </div>
  );
};

export default AIAnalysis;
